#include "checkinpage.h"
#include "ui_checkinpage.h"
#include "sqlhelper.h"
#include "usermanager.h"
#include "loginwindow.h"
#include <QMessageBox>

CheckinPage::CheckinPage(QWidget *parent)
    : MyWidget(parent)
    , ui(new Ui::CheckinPage)
{
    ui->setupUi(this);
    // if (UserManager::getInstance().isLogin())
        loadUserData();
}

void CheckinPage::loadUserData()
{
    QList<QVariantList> checkins;
    if (UserManager::getInstance().isLogin())
        checkins = SqlHelper::getInstance().queryCheckIn(UserManager::getInstance().getUsername());
    else
        checkins = SqlHelper::getInstance().queryCheckIn();

    ui->tableWidgetCheckIn->clearContents();
    ui->tableWidgetCheckIn->setRowCount(0);

    ui->tableWidgetCheckIn->setColumnCount(8);
    ui->tableWidgetCheckIn->setHorizontalHeaderLabels(QStringList()
            << "编号" << "姓名" << "学号" << "打卡日期" << "打卡时间" << "打卡状态" << "备注" << "创建日期");

    ui->tableWidgetCheckIn->horizontalHeader()->setStretchLastSection(true); // 占据整个宽度

    for (const QVariantList &checkin : checkins)
    {
        int row = ui->tableWidgetCheckIn->rowCount();
        ui->tableWidgetCheckIn->insertRow(row);

        ui->tableWidgetCheckIn->setItem(row, 0, new QTableWidgetItem(checkin[0].toString()));
        ui->tableWidgetCheckIn->setItem(row, 1, new QTableWidgetItem(checkin[1].toString()));
        ui->tableWidgetCheckIn->setItem(row, 2, new QTableWidgetItem(checkin[2].toString()));
        ui->tableWidgetCheckIn->setItem(row, 3, new QTableWidgetItem(checkin[3].toString()));
        ui->tableWidgetCheckIn->setItem(row, 4, new QTableWidgetItem(checkin[4].toString()));
        ui->tableWidgetCheckIn->setItem(row, 5, new QTableWidgetItem(checkin[5].toString()));
        ui->tableWidgetCheckIn->setItem(row, 6, new QTableWidgetItem(checkin[6].toString()));
        ui->tableWidgetCheckIn->setItem(row, 7, new QTableWidgetItem(checkin[7].toString()));
    }
}

void CheckinPage::on_pushButtonExit_clicked()
{
    close();
}

void CheckinPage::on_pushButtonCheckin_clicked()
{

    if (!UserManager::getInstance().isLogin())
    {
        QMessageBox::information(this, "请先登录", "您还未登录，请先登录！");

        LoginWindow *loginWindow = new LoginWindow;
        loginWindow->show();

        connect(loginWindow, &LoginWindow::loginSucc, this, &CheckinPage::onLoginSucc);
    }
    else
    {
        SqlHelper& sqlHelper = SqlHelper::getInstance();

        if (sqlHelper.insertCheckIn(UserManager::getInstance().getUsername())) {
            QMessageBox::information(this, "Success", "打卡成功！");
            loadUserData();
        }
        else {
            QMessageBox::critical(this, "Error", "打卡失败！");
        }
    }
}

void CheckinPage::onLoginSucc()
{
    if (UserManager::getInstance().getRole() != UserManager::User)
        close();
    else
        loadUserData();
}

